package com.hh.bss.auth.filter;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.entity.SystemRoleDataControl;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.cache.SystemRoleDataCache;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.CustomerBd;
import com.hh.bss.project.entity.SearchProject;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.util.BeanUtils;
import com.hh.bss.util.StringHelper;

public class UpdateDeleteFilter extends HttpServlet implements Filter {
	private static Map projectURLMap = new HashMap();
	private static Map jobURLMap = new HashMap();
	static {

		// 项目
		projectURLMap.put("/project/searchProject/extupdate.do", "修改项目");
		projectURLMap.put("/project/searchProjectCcList/extsave.do", "新增CC记录");
		//
		projectURLMap.put("/project/searchProjectCcList/extcccvsave.do", "新增CC人选");
		// projectURLMap.put("/project/searchProjectCcList/extupdate.do",
		// "修改CC记录");
		// projectURLMap.put("/project/searchProjectCcList/extdelete.do",
		// "删除CC记录");

		// projectURLMap.put("/project/contractJobCvRecom/extsave.do",
		// "新增人选推荐");

		projectURLMap.put("/project/searchProject/extcompanyjoin.do", "添加目标公司到项目");
		projectURLMap.put("/project/searchProjectCompany/extdelete.do", "删除目标公司");
		// projectURLMap.put("/project/searchProjectCv/cvJoinPorject.do",
		// "添加人选到CC项目");
		projectURLMap.put("/project/searchProjectCv/extdelete.do", "删除CC项目人选");
		// projectURLMap.put("/project/contractJobSearchProject/extsave.do",
		// "新增项目相关职位"); //url有问题
		projectURLMap.put("/project/contractJobSearchProject/extdelete.do", "删除项目相关职位");
		projectURLMap.put("/project/searchProjectCvCrm/extsave.do", "新增联系记录");
		// projectURLMap.put("/project/searchProjectCvCrm/extupdate.do",
		// "修改联系记录");
		// projectURLMap.put("/project/searchProjectCvCrm/extdelete.do",
		// "删除联系记录");

		// 职位

		jobURLMap.put("/project/contractJob/extupdate.do", "修改职位");

		jobURLMap.put("/project/contractJobAttachment/extsave.do", "新增职位附件");
		// jobURLMap.put("/project/contractJobAttachment/extupdate.do",
		// "修改职位附件");
		// jobURLMap.put("/project/contractJobAttachment/extdelete.do",
		// "删除职位附件");

		// jobURLMap.put("/project/contractJobCvRecom/extupdate.do", "修改人选推荐");
		// jobURLMap.put("/project/contractJobCvRecom/extdelete.do", "删除人选推荐");

		jobURLMap.put("/project/contractJobPartner/extsave.do", "新增职位参与人");
		// jobURLMap.put("/project/contractJobPartner/extupdate.do", "修改职位参与人");
		// jobURLMap.put("/project/contractJobPartner/extdelete.do", "删除职位参与人");

		jobURLMap.put("/project/contractJobCvBackground/extsave.do", "新增人选背景调查");
		// jobURLMap.put("/project/contractJobCvBackground/extupdate.do",
		// "修改人选背景调查");
		// jobURLMap.put("/project/contractJobCvBackground/extdelete.do",
		// "删除人选背景调查");

		jobURLMap.put("/project/contractJobCvOffer/extsave.do", "新增职位Offer");
		jobURLMap.put("/project/contractJobCvOffer/extupdate.do", "新增职位附件");
		jobURLMap.put("/project/contractJobCvOffer/extdelete.do", "删除职位Offer");

		jobURLMap.put("/project/contractJobCvCrm/extsave.do", "新增成功人选跟进");
		// jobURLMap.put("/project/contractJobCvCrm/extupdate.do", "修改成功人选跟进");
		// jobURLMap.put(" /project/contractJobCvCrm/extdelete.do", "删除成功人选跟进");

	}

	private final int HAS_PERMISSION = 0, NOT_LOGIN = 1, NO_PERMISSION = 2;

	private boolean hasMyAuth(OnlineUser onlineUser, String url, String entity, Serializable pk) {
		Class c = null;

		if (onlineUser == null || onlineUser.getUsername() == null)
			return false;

		// 如果是GM角色，则不做控制
		// if(SystemUserCache.isRole(onlineUser.getId(), new Integer(6))) return
		// true;
		if (ConstantDic.ADMIN_USER.equals(onlineUser.getUsername()))
			return true;
		//

		try {

			c = Class.forName(entity);
			if (c == null)
				return false;
			Object o = SystemUserCache.getEntity(entity, pk);
			// System.out.println(BeanUtils.isExistsProperty(CustomerBd.class,"creator")+"--"+BeanUtils.isExistsProperty(o.getClass(),"creator1"));

			String creator = null;

			if (BeanUtils.isExistsProperty(o.getClass(), "creator")) {
				creator = BeanUtils.getProperty(o, "creator");

			} else if (BeanUtils.isExistsProperty(o.getClass(), "bd_account")) {
				// 没有creator,查询uploader,暂时为了兼容customer_bd.bd_account
				creator = BeanUtils.getProperty(o, "bd_account");

			} else if (BeanUtils.isExistsProperty(o.getClass(), "uploader")) {
				// 没有creator,查询uploader,暂时为了兼容
				creator = BeanUtils.getProperty(o, "uploader");

			}
			if (creator == null)
				return true;
			if (onlineUser.getUsername().equals(creator))
				return true;
			// org.apache.commons.beanutils.BeanUtils.g
			// org.apache.commons.beanutils.BeanUtilsBean.getInstance().ge

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	private boolean isNeedAuth(String url) {

		/*
		 * String type=SystemRoleDataCache.getUrlType(url);
		 * 
		 * if (SystemRoleDataControl.CONTROL_TYPE_DELETE.equals(type)||
		 * SystemRoleDataControl.CONTROL_TYPE_UPDATE.equals(type)){ return true;
		 * }
		 */

		// 简历，公司，客户的暂时不做控制(除附件外)
		//

		//业绩分配的 单独处理
		if (isJobOfferPartner(url)) {
			return false;
		}
		
		if (url.indexOf("/talent/") >= 0 && url.indexOf("/talent/cvAttachment/") < 0)
			return false;
		if (url.indexOf("/customer/") >= 0 && url.indexOf("/customer/customerContractAttachment/") < 0)
			return false;
		if (url.endsWith("extdelete.do"))
			return true;
		else if (url.endsWith("extupdate.do"))
			return true;

		return false;
	}

	private String getClassName(String url) {
		String className = "";
		try {
			String[] strs = url.split("/");

			if (strs.length == 4) {

				className = "com.tb.bss." + strs[1] + ".entity." + strs[2].substring(0, 1).toUpperCase() + strs[2].substring(1);

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return className;
	}

	private void outNoAuth(HttpServletResponse resp) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("list", new ArrayList());
		result.put("success", false);
		result.put("msg", "对不起，不是您自己的记录,您没有该记录的操作权限!");
		result.put("message", "对不起，不是您自己的记录，您没有该记录的操作权限!");
		outJson(resp, result);
	}

	private void outNoProjectAuth(HttpServletResponse resp) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("list", new ArrayList());
		result.put("success", false);
		result.put("msg", "对不起，您没有该项的操作权限!");
		result.put("message", "对不起，您没有该项的操作权限!");
		outJson(resp, result);
	}

	private boolean doPrject(OnlineUser onlineUser, String className, HttpServletRequest req, String pageURI) {

		String pid = req.getParameter("projectId");
		String sid = req.getParameter("id");
		Integer projectId = com.hh.bss.util.StringHelper.parseInteger(pid, 0);
		Integer id = com.hh.bss.util.StringHelper.parseInteger(sid, 0);
		SearchProject searchProject = null;

		// 管理员不做限制
		if (ConstantDic.ADMIN_USER.equals(onlineUser.getUsername()))
			return true;

		try {
			searchProject = (SearchProject) SystemUserCache.getEntity("com.tb.bss.project.entity.SearchProject", projectId);
		} catch (Exception e) {
		}
		if ("/project/searchProject/extupdate.do".equals(pageURI)) {
			try {
				searchProject = (SearchProject) SystemUserCache.getEntity("com.tb.bss.project.entity.SearchProject", id);
			} catch (Exception e) {
			}
		}
		// projectids
		if ("/project/searchProject/extcompanyjoin.do".equals(pageURI)) {
			try {

				String projectids = req.getParameter("projectids");
				Integer projectid = com.hh.bss.util.StringHelper.parseInteger(projectids, 0);
				searchProject = (SearchProject) SystemUserCache.getEntity("com.tb.bss.project.entity.SearchProject", projectid);
			} catch (Exception e) {
			}
		}

		String owner = "";
		String partner = "";

		if (searchProject != null) {
			// 取项目拥有人，项目参与人
			owner = searchProject.getAccount();
			partner = "," + StringHelper.formatNullValue(searchProject.getPartner(), "") + ",";
			System.out.println("fsdfdsf002.....");

			// 项目信息的修改，只有项目拥有人才可以
			if ("/project/searchProject/extupdate.do".equals(pageURI)) {
				if (!onlineUser.getUsername().equals(owner))
					return false;
			}
			// 项目拥有人 和 项目参与人可以新增项目下相关的信息
			// 非项目相关人员，不可以做操作
			// if(pageURI.endsWith("extsave.do")){
			// if
			// (!onlineUser.getUsername().equals(owner)&&(partner.indexOf(","+onlineUser.getUsername()+",")<0))
			// return false;
			//
			// }
			if (!onlineUser.getUsername().equals(owner) && (partner.indexOf("," + onlineUser.getUsername() + ",") < 0))
				return false;

		}

		return true;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse resp = (HttpServletResponse) response;

		String pageURI = req.getRequestURI().replaceFirst(req.getContextPath(), "");

		OnlineManager onlineManager = new OnlineManager(req, resp);
		OnlineUser onlineUser = null;
		if (onlineManager != null) {
			onlineUser = onlineManager.getOnlineUser();
		}
		String className = getClassName(pageURI);
		// 如果是CC项目的新增，更新和删除操作
		if (projectURLMap.containsKey(pageURI)) {
			System.out.println("projectURLMap:" + pageURI);
			if (!doPrject(onlineUser, className, req, pageURI)) {
				// 没有权限
				outNoProjectAuth(resp);
				return;
			}

		}
		// jobURLMap
		// 如果是 职位的更新和删除操作
		// else if (jobURLMap.containsKey(pageURI)){

		// }
		else if (isNeedAuth(pageURI)) {

			if (!StringHelper.isEmpty(className)) {
				String ids = request.getParameter("ids");
				String id = request.getParameter("id");

				if (!StringHelper.isEmpty(ids)) {
					String[] idarray = ids.split(",");
					for (int i = 0; i < idarray.length; i++) {

						java.lang.Integer pkid = new java.lang.Integer((String) idarray[i]);
						if (!hasMyAuth(onlineUser, pageURI, className, pkid)) {
							// 没有权限
							outNoAuth(resp);
							return;
						}

					}
				}
				if (!StringHelper.isEmpty(id)) {

					java.lang.Integer pkid = new java.lang.Integer(id);
					if (!hasMyAuth(onlineUser, pageURI, className, pkid)) {
						// 没有权限
						outNoAuth(resp);
						return;
					}
				}

			}

		}

		filterChain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	// 单独处理业绩分配 不是创建人()
	public boolean isJobOfferPartner(String url) {
		System.out.println("进入判断......."+url);
		if (url != null && !"".equals(url.trim())) {
			if ("/project/contractJobOfferPartner/extupdate.do".equals(url)) {
				System.out.println("进入判断里面了......."+url);
				return true;
			}

		}
		return false;
	}

}
